package org.study.lucene.api.index;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.*;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.study.lucene.api.constant.PathConstants;

import java.io.File;

/**
 * 参考 https://cloud.tencent.com/developer/article/1023215
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2025年02月07日
 */
public class LuceneTest02 {
    public static void main(String[] args) throws Exception {
        create();
        search("man");
        insert();
        delete("text5");
        update();
    }

    /**
     * 建立索引
     */
    public static void create() throws Exception {
        String text1 = "hello,man!";
        String text2 = "goodbye,man!";
        String text3 = "hello,woman!";
        String text4 = "goodbye,woman!";
        long start = System.currentTimeMillis();
        try (Directory directory = FSDirectory.open(new File(PathConstants.INDEX_PATH).toPath());
             Analyzer analyzer = new StandardAnalyzer()) {
            IndexWriterConfig config = new IndexWriterConfig(analyzer);
            try (IndexWriter indexWriter = new IndexWriter(directory, config)) {
                Document doc1 = new Document();
                doc1.add(new TextField("filename", "text1", Store.YES));
                doc1.add(new TextField("content", text1, Store.YES));
                indexWriter.addDocument(doc1);

                Document doc2 = new Document();
                doc2.add(new TextField("filename", "text2", Store.YES));
                doc2.add(new TextField("content", text2, Store.YES));
                indexWriter.addDocument(doc2);

                Document doc3 = new Document();
                doc3.add(new TextField("filename", "text3", Store.YES));
                doc3.add(new TextField("content", text3, Store.YES));
                indexWriter.addDocument(doc3);

                Document doc4 = new Document();
                doc4.add(new TextField("filename", "text4", Store.YES));
                doc4.add(new TextField("content", text4, Store.YES));
                indexWriter.addDocument(doc4);

                indexWriter.commit();
            }
        }
        System.out.println("创建索引耗时：" + (System.currentTimeMillis() - start) + "ms\n");
    }

    /**
     * 关键字查询
     *
     * @param searchKey 搜索关键字
     */
    public static void search(String searchKey) throws Exception {
        try (Directory directory = FSDirectory.open(new File(PathConstants.INDEX_PATH).toPath());
             DirectoryReader directoryReader = DirectoryReader.open(directory);
             Analyzer analyzer = new StandardAnalyzer()) {
            IndexSearcher indexSearcher = new IndexSearcher(directoryReader);
            QueryParser parser = new QueryParser("content", analyzer);
            Query query = parser.parse(searchKey);
            ScoreDoc[] hits = indexSearcher.search(query, 2, Sort.INDEXORDER).scoreDocs;
            StoredFields storedFields = indexSearcher.storedFields();
            for (int i = 0; i < hits.length; i++) {
                Document hitDoc = storedFields.document(hits[i].doc);
                System.out.println(hitDoc.get("filename"));
                System.out.println(hitDoc.get("content"));
            }
        }
    }


    /**
     * 增加索引
     */
    public static void insert() throws Exception {
        String text5 = "hello,goodbye,man,woman";
        long start = System.currentTimeMillis();
        try (Directory directory = FSDirectory.open(new File(PathConstants.INDEX_PATH).toPath());
             Analyzer analyzer = new StandardAnalyzer()) {
            IndexWriterConfig config = new IndexWriterConfig(analyzer);
            try (IndexWriter indexWriter = new IndexWriter(directory, config)) {
                Document doc1 = new Document();
                doc1.add(new TextField("filename", "text5", Store.YES));
                doc1.add(new TextField("content", text5, Store.YES));
                indexWriter.addDocument(doc1);
                indexWriter.commit();
            }
        }
        System.out.println("增加索引耗时：" + (System.currentTimeMillis() - start) + "ms\n");
    }

    /**
     * 删除索引
     *
     * @param delKey 删除的关键字
     */
    public static void delete(String delKey) throws Exception {
        long start = System.currentTimeMillis();
        try (Directory directory = FSDirectory.open(new File(PathConstants.INDEX_PATH).toPath());
             Analyzer analyzer = new StandardAnalyzer()) {
            IndexWriterConfig config = new IndexWriterConfig(analyzer);
            try (IndexWriter indexWriter = new IndexWriter(directory, config)) {
                indexWriter.deleteDocuments(new Term("filename", delKey));
            }
        }
        System.out.println("删除索引耗时：" + (System.currentTimeMillis() - start) + "ms\n");
    }

    /**
     * 更新索引
     */
    public static void update() throws Exception {
        String text1 = "update,hello,man!";
        long start = System.currentTimeMillis();
        try (Directory directory = FSDirectory.open(new File(PathConstants.INDEX_PATH).toPath());
             Analyzer analyzer = new StandardAnalyzer()) {
            IndexWriterConfig config = new IndexWriterConfig(analyzer);
            try (IndexWriter indexWriter = new IndexWriter(directory, config)) {
                Document doc1 = new Document();
                doc1.add(new TextField("filename", "text1", Store.YES));
                doc1.add(new TextField("content", text1, Store.YES));
                indexWriter.updateDocument(new Term("filename", "text1"), doc1);
            }
        }
        System.out.println("更新索引耗时：" + (System.currentTimeMillis() - start) + "ms\n");
    }
}
